<template>
  <div class="app-container">
    <el-form  label-width="120px" v-loading="loading" >

      <el-form-item  v-for="(item,index) in list" :key="index" :label="item.description+'：'">
        <el-upload v-if="item.key=='qr_code'"
          class="avatar-uploader"
          :action="host+'/guard/upload?module=setting&type='+index"
          :show-file-list="false"
          :on-success="handleAvatarSuccess">
          <img v-if="list[index].val" :src="host+list[index].val" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-input v-else v-model="item.val"></el-input>
      </el-form-item>
      <el-form-item>
        <!--<el-button @click="add" type="danger">添加</el-button>-->
        <el-button @click="onSubmit" type="primary">提交</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
  import { myGet, myPost } from '@/utils/myUtils'
  const urlLst = '/guard/site/setting/index'
  const urlAdd = '/guard/site/setting/index'

  export default {
    data() {
      return {
        list:[],
        loading:false,
        host:process.env.VUE_APP_HOST
      }
    },
    methods: {
      async getRecords(){
        await myGet(urlLst).then(res=>{
          this.list = res.data.records
        })
      },
      add(){
        this.list.push({
          id:0,
          description:'',
          key:'',
          val:'',
        })
      },
      handleAvatarSuccess(res, file) {
        if(res.status){
          const index = res.data.records.type
          this.list[index].val = res.data.records.filePath
        }else{
          this.$message.error('上传失败!')
        }
      },
      onSubmit() {
        this.loading = true
        myPost(urlAdd,{ settings:this.list }).then(res=>{
          this.loading = false
          if(res.status){
            this.$message.success(res.msg);
          }
        })
      }
    },
    mounted() {
      this.getRecords().then(res=>{
        if(this.list.length<=0){
          this.add()
        }
      })


    },
  }
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
